package org.az.netty_study.p03_nio组件之selector._3_单线程selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 这节介绍使用可写事件来处理一次写不完的情况
 * 当一次没写完缓冲区就满了，不会等待缓冲区发送完清空，而是处理其他事件，当缓冲区可以继续写入时，就会触发可写事件
 */
public class WriteServer1 {
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        //创建服务器channel，并注册给Selector
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(9996));
        ssc.configureBlocking(false);
        ssc.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            selector.select();
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = keys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    SelectionKey scKey = sc.register(selector, SelectionKey.OP_READ);
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < 99999999; i++) {
                        sb.append('a');
                    }
                    ByteBuffer buffer = ByteBuffer.wrap(sb.toString().getBytes());
                    int writeCount = sc.write(buffer);
                    System.out.println(writeCount);
                    if (buffer.hasRemaining()) {
                        //如果一次没写完，关注可写事件
                        scKey.interestOps(scKey.interestOps() | SelectionKey.OP_WRITE);
                        //把未读完的数据挂载到scKey上
                        scKey.attach(buffer);
                    }
                }
                //将来缓冲区空出来后，就会触发可写事件
                else if (key.isWritable()) {
                    SocketChannel sc = (SocketChannel)key.channel();
                    ByteBuffer buffer = (ByteBuffer)key.attachment();
                    //接着上次没读完的继续读(不用修改buffer内部指针状态)
                    int writeCount = sc.write(buffer);
                    System.out.println(writeCount);
                    //如果读完了，取消关注可写事件
                    if (!buffer.hasRemaining()) {
                        key.attach(null);
                        key.interestOps(key.interestOps() - SelectionKey.OP_WRITE);
                    }
                }
            }
        }
    }
}
